#!/usr/bin/env python
import os
import logging
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext import db
from google.appengine.ext.webapp.util import login_required
from models import *
from django.utils import simplejson
from datetime import datetime, timedelta
import time
from google.appengine.api.urlfetch import fetch
from google.appengine.api import mail
from xml.sax import saxutils
import hmac

SENDER = 'cia-notifier <underbluewaters@gmail.com>'

class MainHandler(webapp.RequestHandler):
    
    @login_required
    def get(self):
        self.response.out.write(template.render('templates/index.html', {
            'projects': db.GqlQuery("SELECT * FROM Project")
        }))
        
    def post(self):
        data = simplejson.loads(self.request.body)
        if 'project_name' not in data:
            logging.error('POST to / did not contain json from google code.')
            self.response.set_status(400)
            return
        projects = db.GqlQuery("SELECT * FROM Project WHERE name = :1", 
            data['project_name'])
        p = None
        for project in projects:
            m = hmac.new(project.secret_key)
            m.update(self.request.body)
            digest = m.hexdigest()
            if digest == self.request.headers["Google-Code-Project-Hosting-Hook-Hmac"]:
                logging.info('found project %s' % (project.name))
                p = project
            else:
                logging.error('secret_key %s did not match for project %s' % (
                    project.secret_key, project.name))
        project = p
        if project is None:
            logging.error('Unknown project %s.' % (data['project_name'],))
            self.response.set_status(400)
            return
        time = datetime.now()
        project.last_update = time
        project.put()
        logging.info('recieved update: %s' % (self.request.body))

        for rev in data['revisions']:
            files = []
            for f in rev['added']:
                files.append("<file>%s</file>" % (f,))
            for f in rev['modified']:
                files.append("<file>%s</file>" % (f,))
            for f in rev['removed']:
                files.append("<file>%s</file>" % (f,))
            url = "http://code.google.com/p/%s/source/detail?r=%s" % (
                project.name, rev['revision'])
            commit = """
                <commit>
                    <author>%s</author>
                    <revision>%s</revision>
                    <log>%s\n%s</log>
                    <url>%s</url>
                    <files>%s</files>
                </commit>
            """ % (saxutils.escape(rev['author']), rev['revision'], 
                saxutils.escape(rev['message']), url, url, "".join(files))
            
            xml = """<message>
                <generator>
                    <name>cia-notifier</name>
                    <version>1.0</version>
                    <url>cia-notifier.appspot.com</url>
                </generator>
                <source>
                    <project>%s</project>
                </source>
                <body>%s</body>
                <timestamp>%s</timestamp>
            </message>
            """ % (project.name, commit, rev['timestamp'])
        
            mail.send_mail(sender=SENDER,
                          to="cia <cia@cia.navi.cx>",
                          # to="chad <chad@underbluewaters.net>",
                          subject="DeliverXML",
                          body=xml)


def main():
    application = webapp.WSGIApplication([('/', MainHandler)],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
